/* eslint-disable no-param-reassign */
import roleApi from '@/api/modules/system/role'
const state = {
  roleData: [],
  // 当前被选中的角色
  selectedRole: null,
  roleTagColors: []
}
// 5 10
function setRoleTagColor (roleData) {
  // eslint-disable-next-line max-len
  const tagColors = ['2BB080', 'FF8762', '8A8A8A', '58ABCE', '5470C6', '68748B', '9E53A6', 'A67032', '6CA63A', 'B18B73', 'D96641', 'A6A032', '1B4759', 'FEA443', '705E78']
  const roleTags = {}
  const maxColorIndex = tagColors.length - 1
  roleData.map((item, index) => {
    roleTags[item.id] = '#' + tagColors[index % maxColorIndex]
  })
  return roleTags
}
const mutations = {
  SET_ROLE_DATA: (state, val) => {
    state.roleData = val
  },
  SET_SELECTED_ROLE: (state, val) => {
    state.selectedRole = val
  },
  SET_ROLE_TAG_COLORS: (state, val) => {
    state.roleTagColors = val
  }
}
const actions = {
  getRoleData ({ commit, state }) {
    return new Promise((resolve, reject) => {
      roleApi.getRoleAllData().then(res => {
        if (!state.selectedRole) {
          const firstRole = res.data && res.data[0]
          if (firstRole) {
            // eslint-disable-next-line max-len
            commit('SET_SELECTED_ROLE', { id: firstRole.id, name: firstRole.name, remark: firstRole.remark, enableMessageNotice: firstRole.enableMessageNotice })
          }
        }
        commit('SET_ROLE_DATA', res.data)
        commit('SET_ROLE_TAG_COLORS', setRoleTagColor(res.data))
        resolve(true)
      }).catch(err => {
        reject(err)
      })
    })
  },
  // eslint-disable-next-line no-unused-vars
  addRoleData ({ commit, dispatch }, data) {
    return new Promise((resolve, reject) => {
      roleApi.addRole(data).then(res => {
        resolve(res.data)
        dispatch('getRoleData')
      }).catch(err => {
        reject(err)
      })
    })
  },
  // eslint-disable-next-line no-unused-vars
  editRoleData ({ commit, dispatch }, data) {
    return new Promise((resolve, reject) => {
      roleApi.editRole(data).then(res => {
        resolve(res.data)
        dispatch('getRoleData')
      }).catch(err => {
        reject(err)
      })
    })
  },
  // eslint-disable-next-line no-unused-vars
  getRoleMenuData ({ commit, dispatch }, data) {
    return new Promise((resolve, reject) => {
      roleApi.getRoleMenuById(data).then(res => {
        resolve(res.data)
        dispatch('getRoleData')
      }).catch(err => {
        reject(err)
      })
    })
  },
  // eslint-disable-next-line no-unused-vars
  deleteRoleData ({ commit, dispatch }, data) {
    return new Promise((resolve, reject) => {
      roleApi.deleteRoles(data).then(res => {
        resolve(res.data)
        dispatch('getRoleData')
      }).catch(err => {
        reject(err)
      })
    })
  }
}
export default {
  state,
  mutations,
  actions
}
